import {_decorator, CCFloat, Collider2D, Component, math, Node, RigidBody2D, v3, Vec2, Vec3} from 'cc';
import {Constant} from '../../config/Constant';
import {ProjectileProperty} from './ProjectileProperty';
import {logUtil} from "../../framework/util/logUtil";

const {ccclass, property} = _decorator;

let tempVelocity: Vec2 = new Vec2()

/**
 * 投射物
 */
@ccclass('Projectile')
export class Projectile extends Component {

    private collider: Collider2D | null = null;

    //刚体
    rigidbody: RigidBody2D | null = null;

    //发射时间
    private startTime: number = 0;

    //当前子弹属性
    projectProperty: ProjectileProperty = new ProjectileProperty();

    //谁发射的
    host: Node | null = null;
    target: Node | null = null;

    //终点方向,单位向量
    destForward: Vec3 = v3()

    //日志控制器
    log = logUtil.instance
    logLevel = "Projectile"

    //线速度
    @property(CCFloat)
    private linearSpeed: number = 0.0;

    start() {
        this.rigidbody = this.node.getComponent(RigidBody2D);
        this.collider = this.node.getComponent(Collider2D);
    }

    //初始化对象池:启动粒子特效
    fire() {
        this.startTime = 0;
        this.projectProperty.expire=true
        Vec3.subtract(this.destForward, this.target.worldPosition, this.node.worldPosition);
        this.destForward.normalize()
    }

    update(deltaTime: number) {
        this.startTime += deltaTime;
        //定时销毁
        if (this.startTime >= this.projectProperty!.liftTime) {
            this.log.log(this.logLevel, `定时消失`)
            this.node.emit(Constant.EVENT_NAME.onProjectileDead, this);
        }

        this.doMove()
    }

    /**
     * 右移
     */
    doMove() {
        // this.log.log(this.logLevel, `doMove${tempVelocity.x}`)
        let speed = this.linearSpeed * this.destForward.length();
        tempVelocity.x = math.clamp(this.destForward.x, -1, 1) * speed;
        tempVelocity.y = math.clamp(this.destForward.y, -1, 1) * speed;
        this.log.log("ORCA", `${this.logLevel + 3}移动预测{
            节点id:${this.node.uuid},
            刚体速度:${tempVelocity},
            目标方向:${this.destForward},
        }`)
        this.rigidbody.linearVelocity = tempVelocity
    }

    //碰撞时的行为
    onTriggerEnter(selfCollider: Collider2D, otherCollider: Collider2D) {
        this.log.log(this.logLevel, `碰撞行为{发起者:${this.host.name},self:${selfCollider.node.name},other:${otherCollider.node.name}}`)
        this.projectProperty!.penetration--;
        if (this.projectProperty!.penetration <= 0) {
            this.node.emit(Constant.EVENT_NAME.onProjectileDead, this)
        }
    }
}

